package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.Code;
import com.itheima.common.MessageConstant;
import com.itheima.common.PageResult;
import com.itheima.common.Result;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
*@author: lzl
*@description:菜品、套餐分类管理-控制器
*@date:Acer
*/

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    /**
    * @description: 功能描述: 菜品、套餐分类-分页列表查询
    * @author: lzl
    * @date: 2022/6/5
    * @param :page,pageSize
    * @return:
    */
    @GetMapping("/page")
    public PageResult page(Integer page, Integer pageSize){
        //1.调用service层执行分页查询
        Page<Category> res = categoryService.page(page, pageSize);
        //2.1检查分页查询结果,为空的话直接返回状态码
        if (res == null){
            return new PageResult(Code.ERROR, MessageConstant.CAT_GET_ERROR);
        }
        //3.获取当前页列表数据和总条数
        List<Category> records = res.getRecords();//获取当前列表数据
        long total = res.getTotal();//获取全部数据总条数
        //封装pageResult返回查询到的结果
        return new PageResult(Code.OK,MessageConstant.CAT_GET_SUCCESS,records,total);
    }

    /**
     * 获取菜品分类列表数据
     * @param type
     * @return
     */
    @GetMapping("/list")
    public Result findAll(@RequestParam(value = "type",required = false)Integer type){
        List<Category> categoryList = categoryService.findAll(type);
        return new Result(Code.OK,MessageConstant.CAT_GET_SUCCESS,categoryList);
    }

    /**
     * 新增菜品、套餐分类
     * @param category
     * @return
     */
    @PostMapping
    public Result save(@RequestBody Category category){
        int count = categoryService.save(category);
        if (count < 1){
            return new Result(Code.ERROR,MessageConstant.CAT_SAVE_ERROR);
        }
        return new Result(Code.OK,MessageConstant.CAT_SAVE_SUCCESS);
    }

    /**
     * 根据id删除菜品分类或者套餐分类
     * @param id
     * @return
     */
    @DeleteMapping
    public Result del(Long id){
        int deleteById = categoryService.deleteById(id);
        if (deleteById < 1){
            return new Result(Code.ERROR,MessageConstant.CAT_DELETE_ERROR);
        }
        return new Result(Code.OK,MessageConstant.CAT_DELETE_SUCCESS);
    }

    /**
     * 更新分类信息
     * @param category
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Category category){
        int row = categoryService.update(category);
        if (row< 1){
            return new Result(Code.ERROR,MessageConstant.CAT_UPDATE_ERROR);
        }

        return new Result(Code.OK,MessageConstant.CAT_UPDATE_SUCCESS);
    }
}
